import _ from "lodash"
import socket from 'socket.io'
import { MessageType, EnterResult, UserInfo, SocketInfo } from './models/socket-io-model'

export default function (
    socket_io: socket.Server,
    socket_dict: { [code: string]: number },
    socket_list: { [index: number]: UserInfo, get_index(): number }
) {

    return function (socket: socket.Socket) {

        let _user_index = socket_list.get_index();
        let _user_info: UserInfo = { id: _user_index, socket_code: socket.id };
        socket_dict[socket.id] = _user_index;
        socket_list[_user_index] = _user_info;

        console.log(`user connected. [${socket.id}]`);

        socket.on("disconnect", (args: any) => {
            // 注销信息
            let idx = socket_dict[socket.id];
            delete socket_dict[socket.id];
            delete socket_list[idx];

            // 向其它人通知下线
            socket_io.emit("user-leave", { id: idx });
            console.log(`user disconnected. [${idx} | ${socket.id}]`);
        });

        socket.emit("conn-info", {
            id: _user_index,
            socket_code: socket.id
        } as SocketInfo);

        socket.on("set-nick-name", ({ nick_name }) => {
            _user_info.nick_name = nick_name;

            console.log(`user set name. [${_user_index} : ${_user_info.nick_name}]`);

            socket.emit("set-nick-name-ret", { status: "success" });
            socket.broadcast.emit("user-changed", _user_info);
        })

        socket.on("enter-chat", () => {
            //console.log(`user enter chat. [${_user_index} : ${_user_info.nick_name}]`);
            socket.broadcast.emit("user-enter", _user_info);
        })

        socket.on("leave-chat", () => {
            //console.log(`user leave chat. [${_user_index} : ${_user_info.nick_name}]`);
            socket.broadcast.emit("user-leave", _user_info);
        })

        socket.on("user-list", () => {
            socket.emit(
                "user-list-ret",
                _.map(socket_list, item => _.pick(item, ['id', 'nick_name', 'socket_code']))
            );
        })

        socket.on("message-send", (item: MessageType) => {
            socket.broadcast.emit("message-recv", item);
        })

        socket.on("message-send-to", (item: MessageType) => {
            console.log(item);
            if (item.to_id) {
                let to_user = _.get(socket_list, item.to_id)
                if(to_user && to_user.socket_code){
                    socket_io.to(to_user.socket_code).emit("message-recv", item);
                }else{
                    // 用户不存在
                }
            }
        })

    };

}